package com.system.cacheCenterBackend.service.cacheService;

import com.system.cacheCenterBackend.service.StringCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Redis String类型缓存服务实现
 */
@Service
public class RedisStringCacheServiceImpl implements StringCacheService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean set(String key, String value, long timeout) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String get(String key) {
        try {
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean delete(String key) {
        try {
            return Boolean.TRUE.equals(stringRedisTemplate.delete(key));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean exists(String key) {
        try {
            return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public int getKeyAccessCount(String key) {
        // 这里可以实现具体的访问计数逻辑
        // 暂时返回0作为默认值
        return 0;
    }

    @Override
    public boolean isHotKey(String key) {
        // 这里可以实现具体的热点key判断逻辑
        // 暂时返回false作为默认值
        return false;
    }

    @Override
    public void resetKeyStatistics(String key) {
        // 这里可以实现具体的统计重置逻辑
    }

    @Override
    public Integer getKeyAccessCountAsync(String key) {
        try {
            return CompletableFuture.supplyAsync(() -> getKeyAccessCount(key)).get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}